package com.henry.base.concurrency.lockfree;

import java.util.concurrent.atomic.AtomicReference;

public class LockFreeStack<V> {
    private AtomicReference<Node<V>> top = new AtomicReference<>();

    public void push(V o){
        Node<V> nextValue=new Node<>(o,null);
        Node<V> oldValue=null;
        do {
            oldValue = top.get();
            nextValue.setNext(oldValue);
        } while (!top.compareAndSet(oldValue, nextValue));
//        oldValue = top.get();
//        nextValue.setNext(oldValue);
//        top.getAndSet(nextValue);
    }

    public V pop(){
        Node<V> oldValue=null;
        Node<V> nextValue=null;
        do {
            oldValue = top.get();
            if (oldValue == null) {
                continue;//如果oldValue为空,则栈内是空的
            }
            nextValue = oldValue.getNext();
            //能进入while条件内,说明在当前线程内,oldValue不为null
        } while (!top.compareAndSet(oldValue, nextValue));
        return oldValue.getValue();
    }

}
